package ${beanPackage};

/**
 * @author: ${Author}
 * @date: ${DATE}
 */

import co.paralleluniverse.fibers.Suspendable;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.SQLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.vertx.ext.sync.Sync.awaitResult;

public class JdbcService {

    private static final Logger logger = LoggerFactory.getLogger(JdbcService.class);

    @Suspendable
    public <R> R transaction(SQLConnection conn, JdbcAble<SQLConnection, R> function) {
        try {
            Void autoCommit = awaitResult(h->conn.setAutoCommit(false, h));
            R r = function.apply(conn);
            Void commit = awaitResult(h->conn.commit(h));
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("transaction", e);
            Void rollback = awaitResult(h->conn.rollback(h));
            throw new RuntimeException("transaction失败");
        }
    }

    @Suspendable
    public <R> R transaction(JDBCClient jdbcClient, JdbcAble<SQLConnection, R> function) {
        try (io.vertx.ext.sql.SQLConnection conn = awaitResult(jdbcClient::getConnection)) {
            return transaction(conn, function);
        }
    }

    @Suspendable
    public <R> R query(JDBCClient jdbcClient, JdbcAble<io.vertx.ext.sql.SQLConnection, R> function) {
        try (SQLConnection conn = io.vertx.ext.sync.Sync.awaitResult(jdbcClient::getConnection)) {
            R data = function.apply(conn);
            return data;
        }
    }
}
